from django.views.generic.base import View
from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import PageNotAnInteger,Paginator

from operation.models import UserFavorite,UserComments,UserBrowse,UserRatings
from movieinfo.models import Movie,MovieParticulars


class AddFavView(View):
    """用户收藏和取消收藏"""
    def post(self,request):
        # 防止后边int(fav_id)时出错
        id=request.POST.get('fav_id',0)
        if not request.user.is_authenticated:
            # 未登录时返回json提示未登录,跳转到登录页面是在ajax中做
            return HttpResponse('{"status":"fail","msg":"用户未登录"}', content_type='application/json')
        exist_record=UserFavorite.objects.filter(user=request.user, movie_id=int(id))
        if exist_record:
            # 如果记录已经存在，表示用户要取消收藏
            exist_record.delete()
            movie=Movie.objects.get(id=int(id))
            movie.fav_nums -= 1
            if movie.fav_nums < 0:
                movie.fav_nums = 0
            movie.save()
            return HttpResponse('{"status":"success","msg":"收藏"}', content_type='application/json')
        else:
            user_fav=UserFavorite()
            if int(id) > 0:
                user_fav.movie_id=int(id)
                user_fav.user=request.user
                user_fav.save()
                movie = Movie.objects.get(id=int(id))
                movie.fav_nums += 1
                movie.save()
                return HttpResponse('{"status":"success","msg":"已收藏"}', content_type='application/json')
            else:
                return HttpResponse('{"status":"success","msg":"收藏出错"}', content_type='application/json')


# 添加评论
class AddCommentsView(View):
    def post(self, request):
        if not request.user.is_authenticated:
            return HttpResponse('{"status":"fail", "msg":"用户未登录"}', content_type='application/json')
        movie_id = request.POST.get('movie_id', 0)
        comments = request.POST.get('comments', '')
        if int(movie_id)> 0 and comments:
            movie_comments = UserComments()  # 实例化
            movie = Movie.objects.get(id= int(movie_id))
            movie_comments.movie = movie
            movie_comments.user = request.user
            movie_comments.comment = comments
            movie_comments.save()
            # return render(request,'playMovie.html',{"status":"success", "msg":"评论成功","movie_comments": movie_comments})
            return  HttpResponse('{"status":"success", "msg":"评论成功"}', content_type='application/json')
        else:
            return HttpResponse('{"status":"fail", "msg":"评论失败"}', content_type='application/json')


# 评级
class AddGradeView(View):
    def post(self,request):
        if not request.user.is_authenticated:
            return HttpResponse('{"status":"fail", "msg":"用户未登录"}', content_type='application/json')
        grade=request.POST.get('add_grade',0)
        movie_id=request.POST.get('movie_id',0)
        if movie_id and grade:
            movie = Movie.objects.get(id=int(movie_id))
            movie_rating = UserRatings.objects.filter(user=request.user,movie=movie)
            if not movie_rating:
                UserRatings.objects.create(user=request.user, movie=movie,ratings=float(grade))
            else:
                movie_rating.update(ratings=float(grade))
            return HttpResponse({"status":"success", "msg":"评级成功","grade":movie_rating.ratings},content_type='application/json')
        else:
            return HttpResponse({"status":"fail", "msg":"评级失败"}, content_type='application/json')


class MovieDetailView(View):
    # 电影详情页
    def get(self, request, movie_id):
        movieId=Movie.objects.get(id= int(movie_id))

        # 点击数加一
        movieId.click_nums += 1
        movieId.save()

        # 获取电影详情信息
        movie_info = MovieParticulars.objects.get(id=int(movie_id))

        # 热门排行
        fav_movie = Movie.objects.all().order_by('-fav_nums')[:10]

        # 收藏
        is_fav = '收藏'
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, movie_id=int(movie_id)):
                is_fav = '已收藏'

        # 显示评论
        comments = UserComments.objects.filter(movie=movieId).order_by('-add_time')
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(comments,8)  # 每页显示8个，从all_classification中取
        comments_page = p.page(page)

        # 显示评分
        ratings=float(0)
        if request.user.is_authenticated:
             ratings=UserRatings.objects.filter(user=request.user, movie=movieId)

        # 记录浏览
        if request.user.is_authenticated:
            if not UserBrowse.objects.filter(user= request.user, movie_id=int(movie_id)):
                UserBrowse.objects.create(user=request.user, movie_id=int(movie_id))

        return render(request, 'playMovie.html', {
            'movie_info': movie_info,
            'fav_movie': fav_movie,
            'is_fav': is_fav,
            'comments_page': comments_page,
            'ratings': ratings,
        })